package com.cmti.skeleton.service.impl;

import com.cmti.skeleton.service.FileService;
import com.cmti.skeleton.util.Constants;
import java.io.File;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

/**
 *
 * @author Danny Lee
 */
@Service
public class FileServiceImpl implements FileService {
    
    private final Log log = LogFactory.getLog(this.getClass());
    
    @Override
    public boolean moveTo(String fileName, String fromPath, String toPath) {
        File oldFile = null;
        File newFile = null;
        //new一个新文件夹
        File newDir = new File(toPath);
        //判断文件夹是否存在
        if (!newDir.exists()) {
            newDir.mkdirs();
        }
        
        oldFile = new File(fromPath + fileName);
        //将文件移到新文件里
        newFile = new File(toPath + oldFile.getName());
        boolean renameTo = oldFile.renameTo(newFile);
        log.debug("移动文件" + fileName + "\t" + renameTo);
        return renameTo;
    }
    
    @Override
    public void deleteFiles(List<String> delList, String dirName) {
        long totalSize = 0;
        for (String value : delList) {
            String[] pics = value.split(",");
            for (String pic : pics) {
                String[] strs = pic.split(":");
                String realName = "";
                if (strs.length > 1) {
                    realName = strs[1];
                } else {
                    realName = strs[0];
                }
                File f = new File(BASE_PATH + dirName + "/" + realName);
                long size = f.length();
                if (f.delete()) {
                    totalSize += size;
                }
            }
        }
    }
    
    @Override
    public void saveFiles(String[] files, List<String> imagesToBeDeleted, String fromPath, String dirName) {
        String toPath = BASE_PATH + dirName + "/";
        for (int i = 0; i < files.length; i++) {
            if (imagesToBeDeleted != null && !imagesToBeDeleted.isEmpty()) {
                imagesToBeDeleted.remove(files[i].trim());
            }
            if (files[i].length() < 1) {
                continue;
            }
            moveTo(files[i], fromPath, toPath);
        }
        
        if (imagesToBeDeleted != null && !imagesToBeDeleted.isEmpty()) {
            for (String s : imagesToBeDeleted) {
                File file = new File(toPath + s);
                file.delete();
            }
        }
    }
}
